package controller;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

import org.activiti.engine.task.Task;
import org.junit.Assert;

import wfm.activiti.ActivitiManager;
import wfm.entities.Address;
import wfm.entities.Customer;
import wfm.entities.Partner;
import wfm.entities.Ticket;
import wfm.entities.User;
import wfm.entities.WFInfo;
import wfm.query.QueryDao;
import wfm.util.email.Mail;
import wfm.util.email.MailAccounts;

import com.web.util.WebUtils;

@ManagedBean(name = "customerController")
@SessionScoped
public class CustomerController {

	@ManagedProperty(value = "#{user}")
	private User user;
	
	@ManagedProperty(value = "#{wfInfo}")
	private WFInfo wfInfo;

	@ManagedProperty(value = "#{renterInformation}")
	private String renterInformation;
	
	private String mailText; 
	private Customer customer;  
	
	@ManagedProperty(value="typeOfDamage")
	private String typeOfDamage; 
	
	@ManagedProperty(value="selectedPartner")
	private String selectedPartner; 
	
//	private List<Partner> partners;
//	private List<Partner> electroDefectPartners;
//	private List<Partner> gasDefectPartners;
//	private List<Partner> waterDamagePartners;
//	private List<Partner> moldDamagePartners;
//	private List<Partner> fireDamagePartners;

	
	
	/** Creates a new instance of LoginControl */
	public CustomerController() {
	}
	
	@PostConstruct
	public void init(){
		customer = new Customer(); 
		customer.setFirstName("Heinz");
		customer.setLastName("Mueller");
		customer.setMailAddress("mueller@mueller.com");
		customer.setAddress(new Address("Karlsplatz 13","Wien","1040","Österreich"));
		customer.setTelNo("06644075390");
		
//		partners = new ArrayList<Partner>();
//		moldDamagePartners = new ArrayList<Partner>();
//		waterDamagePartners = new ArrayList<Partner>();
//		fireDamagePartners = new ArrayList<Partner>();
//		gasDefectPartners = new ArrayList<Partner>();
//		electroDefectPartners = new ArrayList<Partner>();
		
//		moldDamagePartners.add(new Partner("Mold Specialists","Lovely Street 1", "066440789", "msp@mold.com"));
//		moldDamagePartners.add(new Partner("Mold Meister","Down Street 1", "5678239", "msp@meister.com"));
//		moldDamagePartners.add(new Partner("Mold AWAY","Fleet Street 1", "056782822", "away@mold.co.uk"));
//		
//		waterDamagePartners.add(new Partner("Plumber School","Lovely Street 1", "066440789", "msp@plumber.com"));
//		waterDamagePartners.add(new Partner("Water Helper","Down Street 1", "5678239", "msp@helper.com"));
//		waterDamagePartners.add(new Partner("Watery","Fleet Street 1", "056782822", "away@water.co.uk"));
//		
//		fireDamagePartners.add(new Partner("Fire Blaster","Lovely Street 1", "066440789", "msp@fire.com"));
//		fireDamagePartners.add(new Partner("Danger Ranger","Down Street 1", "5678239", "msp@fire.com"));
//		fireDamagePartners.add(new Partner("Fireman","Fleet Street 1", "056782822", "away@fire.co.uk"));
//		
//		gasDefectPartners.add(new Partner("GAS Blaster","Lovely Street 1", "066440789", "msp@gasbl.com"));
//		gasDefectPartners.add(new Partner("GASYYY","Lovely Street 1", "066440789", "msp@gasless.com"));
//		gasDefectPartners.add(new Partner("GASLESS","Bloom Street 1", "23232323", "msp@gas.com"));
//		
//		electroDefectPartners.add(new Partner("Ede","Lovely Street 1", "066440789", "msp@e.com"));
//		electroDefectPartners.add(new Partner("EDEFECT","Big Street 1", "066440789", "msp@e.com"));
//		electroDefectPartners.add(new Partner("onlyE","Bloom Street 1", "066440789", "msp@e.com"));
//		electroDefectPartners.add(new Partner("E-WAY","Low Street 1", "066440789", "msp@way.com"));
	}
	
	

//	public String getSelectedPartner() {
//		return selectedPartner;
//	}
//
//	public void setSelectedPartner(String selectedPartner) {
//		this.selectedPartner = selectedPartner;
//	}
//
//	public String getTypeOfDamage() {
//		return typeOfDamage;
//	}
//
//	public void setTypeOfDamage(String typeOfDamage) {
//		this.typeOfDamage = typeOfDamage;
//	}

//	public List<Partner> getPartners() {
//		return partners;
//	}
//
//	public void setPartners(List<Partner> partners) {
//		this.partners = partners;
//	}

//	public String getMailText() {
//		return mailText;
//	}
//
//
//
//	public void setMailText(String mailText) {
//		this.mailText = mailText;
//	}



//	public Customer getCustomer() {
//		return customer;
//	}
//
//
//
//	public void setCustomer(Customer customer) {
//		this.customer = customer;
//	}
	
	public String submit1() {

		String nextPage = "";
		
		System.out.println("Submit1");

		// Retrieving Activiti engine
		ActivitiManager manager = ActivitiManager.getInstance();

		try {
			// Submitting task form
			String taskId = this.getTaskId();
			//FIXME: property!!!???
			//manager.getProcessEngine().getFormService().submitTaskFormData(taskId, null);
			manager.getTaskRuntimeService().complete(this.getTaskId());

		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}

		// Check for any execution errors
		String instanceId = this.getInstanceId();
		
		List<Task> tasks = manager.getProcessEngine().getTaskService()
				.createTaskQuery().taskCandidateGroup(getActUserGroup())
				.processInstanceId(instanceId).list();
		
		if (tasks.size() > 0) {
			// Get first task
			Task task = tasks.get(0);
			this.setTaskId(task.getId());

			nextPage = QueryDao.getFormKey(this.getTaskId());
			QueryDao.setAssigneeToTask(task, this.getUser().getName());
			this.setTaskId(task.getId());
		}

		return WebUtils.redirect(nextPage);
	}



	/**
	 * Returns the UserGroup of the logged-in User
	 * @return
	 */
	private String getActUserGroup(){
		
		String userGroup=User.GROUP_DESKTOPWORKER;
		
		if(this.user!=null){
			userGroup = this.user.getUserGroup();
		}
		
		return userGroup;
	}

//	public String finishRepairTicket() {
//
//		Partner selectedPartner = null;
//		
//		for(Partner partner:partners){
//			if(partner.getName().equals(this.selectedPartner))
//				selectedPartner = partner; 
//		}
//		
//		System.out.println(selectedPartner.getName());
//		
//		String nextPage = "myTasks";
//		
//		
//
//		// Retrieving Activiti engine
//		ActivitiManager manager = ActivitiManager.getInstance();
//
//		try {
//			manager.getTaskRuntimeService().complete(this.getTaskId());
//
//		} catch (Exception e) {
//			e.printStackTrace();
//			return "";
//		}
//
//		// Check for any execution errors
//		String instanceId = this.getInstanceId();
//		
//		Task task=QueryDao.getNextTaskAndSetAssignee(instanceId, this.user);  //holt sich den nächsten Task zur Gruppe und setzt Asignee
//		
//		if(task!=null){
//			this.setTaskId(task.getId());
//			nextPage = QueryDao.getFormKey(this.getTaskId());
//		}
//
//		return WebUtils.redirect(nextPage);
//	}
	
	
	public String finishProtocolPreparation() {

		String nextPage = "myTasks";
		
		// Retrieving form fields
		Map<String, String> prop = new HashMap<String, String>();		
		prop.put("firstName", null);
		prop.put("lastName", null);
		prop.put("telNo", null);
		prop.put("street", null);
		prop.put("mailAddress", null);
		prop.put("description", null);
		prop.put("zip", null);
		prop.put("city", null);
		prop.put("country",null);
		
		// Retrieving Activiti engine
		ActivitiManager manager = ActivitiManager.getInstance();	

		try {
			// Submitting task form -> go to next Activity
			String taskId = this.getTaskId();
			manager.getProcessEngine().getFormService().submitTaskFormData(taskId, prop);

		} catch (Throwable t) {
			 t.printStackTrace();
			FacesContext fc = FacesContext.getCurrentInstance();
			FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR,"Problem with Webservice!!!", null);
			fc.addMessage(null, msg);
			fc.renderResponse();

			return "";
		}
		
		// Check for any execution errors
		String instanceId=this.getInstanceId();
		
		String taskError = manager.getTaskError(instanceId);
		if (taskError != null && !taskError.equals(""))
		{	
			List<Task> tasks = manager.getProcessEngine().getTaskService().createTaskQuery().taskCandidateGroup(getActUserGroup()).processInstanceId(instanceId).list();
			if (tasks.size() > 0)
			{
				// Get first task
				Task task = tasks.get(0);
				this.setTaskId(task.getId());
				nextPage = QueryDao.getFormKey(this.getTaskId());
				QueryDao.setAssigneeToTask(task, this.getUser().getName());
			}
			
			FacesContext fc = FacesContext.getCurrentInstance();
			FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, taskError, null);
		    fc.addMessage(null, msg);
		    fc.renderResponse();
		}else{
				
			Address adr = null;
			//get Address from ProcessInstance
			adr = (Address) QueryDao.getVariableToProcessById(instanceId, "address");
			
			
			if(adr!=null){
				
				nextPage="myTasks";
				
				List<Task> tasks = manager.getProcessEngine().getTaskService().createTaskQuery().taskCandidateGroup(getActUserGroup()).processInstanceId(instanceId).list();
				if (tasks.size() > 0)
				{
					// Get first task
					Task task = tasks.get(0);
					this.setTaskId(task.getId());
					nextPage = QueryDao.getFormKey(this.getTaskId());
					QueryDao.setAssigneeToTask(task, this.getUser().getName());
				}
				
			}else{
				
				List<Task> tasks = manager.getProcessEngine().getTaskService().createTaskQuery().taskCandidateGroup(getActUserGroup()).processInstanceId(instanceId).list();
				if (tasks.size() > 0)
				{
					// Get first task
					Task task = tasks.get(0);
					this.setTaskId(task.getId());
					QueryDao.setAssigneeToTask(task, this.getUser().getName());
					
					//FIXME
					//nextPage = QueryDao.getFormKey(this.getTaskId());
					System.out.println("ADR Null nextPage: " + nextPage);
					this.setTaskId(task.getId());
				}
				
				FacesContext fc = FacesContext.getCurrentInstance();
				FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "No customer found with this address.", null);
			    fc.addMessage(null, msg);
			    fc.renderResponse();

			}
			
		}
		
		return WebUtils.redirect(nextPage);
	}
	
	
	public String finishCheckWork() {

		String nextPage = "myTasks";
		
		System.out.println("finishedWorkCheck");

		// Retrieving Activiti engine
		ActivitiManager manager = ActivitiManager.getInstance();

		try {
			manager.getTaskRuntimeService().complete(this.getTaskId());

		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}

		// Check for any execution errors
		String instanceId = this.getInstanceId();
		
		Task task=QueryDao.getNextTaskAndSetAssignee(instanceId, this.user);  //holt sich den nächsten Task zur Gruppe und setzt Asignee
		
		if(task!=null){
			this.setTaskId(task.getId());
			nextPage = QueryDao.getFormKey(this.getTaskId());
		}

		return WebUtils.redirect(nextPage);
	}
	
	
	public String finishProtocol() {

		String nextPage = "myTasks";
		
		System.out.println("finishedWorkCheck");

		// Retrieving Activiti engine
		ActivitiManager manager = ActivitiManager.getInstance();

		try {
			manager.getTaskRuntimeService().complete(this.getTaskId());

		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}

		// Check for any execution errors
		String instanceId = this.getInstanceId();
		
		Task task=QueryDao.getNextTaskAndSetAssignee(instanceId, this.user);  //holt sich den nächsten Task zur Gruppe und setzt Asignee
		
		if(task!=null){
			this.setTaskId(task.getId());
			nextPage = QueryDao.getFormKey(this.getTaskId());
		}

		return WebUtils.redirect(nextPage);
	}
	
	
	public String finishTransferCheck() {

		String nextPage = "myTasks";
		
		System.out.println("finishedWorkCheck");

		// Retrieving Activiti engine
		ActivitiManager manager = ActivitiManager.getInstance();

		try {
			manager.getTaskRuntimeService().complete(this.getTaskId());

		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}

		// Check for any execution errors
		String instanceId = this.getInstanceId();
		
		Task task=QueryDao.getNextTaskAndSetAssignee(instanceId, this.user);  //holt sich den nächsten Task zur Gruppe und setzt Asignee
		
		if(task!=null){
			this.setTaskId(task.getId());
			nextPage = QueryDao.getFormKey(this.getTaskId());
		}

		return WebUtils.redirect(nextPage);
	}
	
	
	public String finishTicket() {

		String nextPage = "myTasks";
		
		System.out.println("finishedWorkCheck");

		// Retrieving Activiti engine
		ActivitiManager manager = ActivitiManager.getInstance();

		try {
			manager.getTaskRuntimeService().complete(this.getTaskId());

		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}

		// Check for any execution errors
		String instanceId = this.getInstanceId();
		
		Task task=QueryDao.getNextTaskAndSetAssignee(instanceId, this.user);  //holt sich den nächsten Task zur Gruppe und setzt Asignee
		
		if(task!=null){
			this.setTaskId(task.getId());
			nextPage = QueryDao.getFormKey(this.getTaskId());
		}

		return WebUtils.redirect(nextPage);
	}
	
//	public String finishInformRenter(){
//		String nextPage = "myTasks";
//		String instanceId = this.getInstanceId();
//		
//		//Ticket holen updaten und wieder speichern
//		Ticket ticket=(Ticket)QueryDao.getVariableToProcessById(instanceId, "ticket");
//		ticket.setRenterInformation(this.renterInformation);
//		QueryDao.saveVariableToProcessById(instanceId, "ticket", ticket);
//		
//		System.out.println("finishedInformRenter");
//
//		// Retrieving Activiti engine
//		ActivitiManager manager = ActivitiManager.getInstance();
//
//		try {
//			manager.getTaskRuntimeService().complete(this.getTaskId());
//
//		} catch (Exception e) {
//			e.printStackTrace();
//			return "";
//		}
//		
//		Task task=QueryDao.getNextTaskAndSetAssignee(instanceId, this.user);  //holt sich den nächsten Task zur Gruppe und setzt Asignee
//		
//		if(task!=null){
//			this.setTaskId(task.getId());
//			nextPage = QueryDao.getFormKey(this.getTaskId());
//		}
//
//		return WebUtils.redirect(nextPage);
//	}
	
//	public String finishInformRenterWithMail(){		
//		//Ticket holen updaten und wieder speichern
//		Ticket ticket=(Ticket)QueryDao.getVariableToProcessById(this.getInstanceId(), "ticket");
//		
//		//send mail 
//		String recipient = "MarkusFriedl@gmx.at";
//        String subject = "Your Ticket ("+ticket.getId()+") has been answered";
//        String text = mailText; 
// 
//        try {
//			Mail.send(MailAccounts.GMX, recipient, subject, text);
//		} catch (Exception e) {
//			Assert.fail();
//		}     
//
//        System.out.println("Sended");
//		
//		
//		//finish
//		return finishInformRenter();
//	}

	/**
	 * Abort Inform Renter
	 * @return
	 */
//	public String abortInformRenter(){
//		return WebUtils.redirect("myTasks");
//	}
	
	public WFInfo getWfInfo() {
		return wfInfo;
	}

	public void setWfInfo(WFInfo wfInfo) {
		this.wfInfo = wfInfo;
	}

	public String getInstanceId() {
		return this.wfInfo.getInstanceId();
	}

	public void setInstanceId(String instanceId) {
		this.wfInfo.setInstanceId(instanceId);
	}

	public String getTaskId() {
		return this.wfInfo.getTaskId();
	}

	public void setTaskId(String taskId) {
		this.wfInfo.setTaskId(taskId);
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

//	public String getRenterInformation() {
//		return renterInformation;
//	}
//
//	public void setRenterInformation(String renterInformation) {
//		this.renterInformation = renterInformation;
//	}
	
//	public void handleDamageChange(){
//		int damage = Integer.parseInt(this.typeOfDamage);
//		
//		switch (damage) {
//		case 1:
//			this.partners = electroDefectPartners;
//			break;
//		case 2:
//			this.partners = waterDamagePartners;
//			break;
//		case 3:
//			this.partners = fireDamagePartners;
//			break;
//		case 4:
//			this.partners = gasDefectPartners;
//			break;
//		case 5:
//			this.partners = moldDamagePartners;
//			break;
//		}
//	}
}
